<?php
/**
* @author moufer<moufer@163.com>
* @copyright (c)2001-2014 Moufersoft
* @website www.modoer.com
*/

!defined('IN_MUDDER') && exit('Access Denied');

/**
* 公众平台配置类
*/
class mc_weixin_role extends ms_base
{

	protected $weixinObj;
	protected $roleData;

	public static function __callStatic($name, $args)
	{
		if(substr($name, 0, 4) != 'read') {
			goto end;
		}
		$fun_name = substr($name, 4);
		if(!$fun_name) {
			$id = (int) $args[0];
			$data = _G('loader')->model('weixin:mp')->read($id);
		} elseif($fun_name == '_site') {
			$data = _G('loader')->model('weixin:mp')->read_site();
		} elseif($fun_name == '_by_sid') {
			$sid = (int) $args[0];
			$data = _G('loader')->model('weixin:mp')->read_by_sid($sid);
		} elseif($fun_name == '_by_city_id') {
			$city_id = (int) $args[0];
			$data = _G('loader')->model('weixin:mp')->read_by_city_id($city_id);
		} else {
			goto end;
		}
		if(!$data) return false;
		return new self($data);

		end:
		show_error(lang('global_op_function_not_exists', $name));
	}

	public function __construct($data)
	{
		parent::__construct();
		foreach ($data as $key => $value) {
			$this->$key = $value;
			if($key == 'config') {
				$this->$key = ms_attr::form_xml($value);
				if(!$this->$key) $this->$key = new ms_attr;
			}
		}
	}

	public function get_weixin()
	{
		if(!$this->weixinObj) {
			$this->weixinObj = new mc_weixin($this);
		}
		return $this->weixinObj;
	}

	public function get_role()
	{
		if(!$this->roleData) {
			if($this->role == 'subject') {
				$this->roleData = _G('loader')->model('item:subject')->read($this->role_id);
			}
		}
		return $this->roleData;
	}

	public function check_use_bind()
	{
		if($this->role == 'subject') {
			$subject = $this->get_role();
			$pid = $subject['pid'];
			$use_bind = S('weixin:use_bind')?explode(',', S('weixin:use_bind')):array();
			return $use_bind && in_array($pid, $use_bind) && $this->status > 0;
		} else {
			return true;
		}
	}

	//获取高级接口需要的access_token信息
	public function getAccessToken()
	{
		//判断是否失效
		if(! $this->access_token || $this->expires_in > 0 && $this->expires_in < _G('timestamp')) {
			if(!$this->_getAccessToken()) return false;
		}
		return $this->access_token;
	}

	//从微信服务器获取access_token
	private function _getAccessToken()
	{
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
		$data = http_get($url);
		if($data) $json = json_decode($data, true);
		if($json['access_token']) {
			$this->access_token = $json['access_token'];
			$this->expires_in = _G('timestamp') + $json['expires_in'];
			//保存到数据库
			_G('loader')->model('weixin:mp')->save_access_token($this->id, $this->access_token, $this->expires_in);
			return true;
		} else {
			log_write('weixin', $url."\n".$data);
			return false;
		}
	}

}

/** end **/